package com.oncliedisk.administrator.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.R;
import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.adapter.FileAdapter;
import com.oncliedisk.administrator.content.FileConfig;
import com.oncliedisk.administrator.model.FileModel;
import com.oncliedisk.administrator.ui.ApplicationActivity;
import com.oncliedisk.administrator.ui.BtActivity;
import com.oncliedisk.administrator.ui.DocumentActivity;
import com.oncliedisk.administrator.ui.MusicActivity;
import com.oncliedisk.administrator.ui.OthersActivity;
import com.oncliedisk.administrator.ui.PhotoActivity;
import com.oncliedisk.administrator.ui.SearchActivity;
import com.oncliedisk.administrator.ui.UploadMusicActivity;
import com.oncliedisk.administrator.ui.UploadPictureActivity;
import com.oncliedisk.administrator.ui.UploadVideoActivity;
import com.oncliedisk.administrator.ui.VideoActivity;
import com.oncliedisk.administrator.utils.FileUtils;
import com.oncliedisk.administrator.utils.MyFileComparator;
import com.oncliedisk.administrator.utils.NameComparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/3.
 * 文件目录页面
 */
public class FragMentFile extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener, AdapterView.OnItemLongClickListener {
    private ListView listview; //ListView
    private FileAdapter mAdapter; //适配器
    private String currId = FileConfig.IS_ROOT; //当前ID
    private String currPosition = "0";
    private static Context context;
    private ImageView sort; //排序图片
    private ImageView newFile; //新建
    private ImageView search;//搜索
    private EditText newFileNmae; //新建文件名
    private Button newFileYes; //确定创建文件夹
    private Button newFileNo; //取消创建文件夹
    private View dialog_view; //Dialog的视图
    AlertDialog.Builder builder;
    private AlertDialog alertDialog; //新建对话框
    private LinearLayout layout; //layout
    private PopupWindow window;
    private TextView order_name; //名字排序
    private TextView order_tiem; //时间排序
    private boolean isTime = true;
    private String paths = "网盘"; //路径
    private TextView tv_path; //路径文本
    private boolean isLongClick = false; //长按状态
    private Button cancel; //取消
    private Button allSelecd; //全选
    private TextView selecedNumber; //当前选中几个
    private RelativeLayout longClickLayout; //长按layout
    private boolean isAllSeleced; //全选状态
    private LinearLayout showLongLayout; //全选状态工具栏
    private ImageView openFile_img; //打开文件图标
    private TextView openFile_txt; //打开文件文字
    private int[] img_grey = {R.drawable.open_grey, R.drawable.down_grey, R.drawable.delete_grey, R.drawable.more_grey};
    private int[] img_white = {R.drawable.open_white, R.drawable.down_white, R.drawable.delete_white, R.drawable.more_white};
    private int currSelseNum; //当前选中了几个
    private List<FileModel> seleedModel; //当前选中的集合对象
    private LinearLayout upload; //上传布局
    private LinearLayout classify; //分类布局
    private GridView gview; //GridView
    private PopupWindow popupWindow; //弹出窗口
    // 图片封装为一个数组
    private int[] icon = {R.mipmap.netdisk_category_document_normal, R.mipmap.netdisk_category_audio_normal,
            R.mipmap.netdisk_category_image_normal, R.mipmap.netdisk_upload_category_video_normal, R.mipmap.netdisk_category_other_normal,
    };
    private String[] iconName = {"文档", "音乐", "图片", "视频", "其他",
    };
    private List<Map<String, Object>> data_list;
    private SimpleAdapter sim_adapter;
    private View gviewParent;
    private GridView gview1;
    private GridView gview2;
    private List<Map<String, Object>> data_list1;
    private SimpleAdapter sim_adapter1;
    private PopupWindow popupWindow1;
    private View gviewParent1;
    private Button button;
    // 图片封装为一个数组
    private int[] icon1 = {R.drawable.netdisk_category_image_normal, R.drawable.netdisk_category_document_normal,
            R.drawable.netdisk_category_audio_normal,
            R.drawable.netdisk_category_bt_normal,
            R.drawable.netdisk_upload_category_video_normal, R.drawable.netdisk_category_apk_normal, R.drawable.netdisk_category_other_normal};
    private String[] iconName1 = {"照片", "文档", "音乐", "BT种子", "视频", "应用", "其他",
    };
    private String postfix; //当前重命名的文件后缀

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_file, null);
        initWeight(view);
        initData();
        initListener();
        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initWeight(View view) {
        listview = (ListView) view.findViewById(R.id.file_main_listview);
        sort = (ImageView) view.findViewById(R.id.file_sort);
        newFile = (ImageView) view.findViewById(R.id.file_newfile);
        search = (ImageView) view.findViewById(R.id.file_search);
        context = getActivity();
        layout = (LinearLayout) view.findViewById(R.id.file_layout);
        tv_path = (TextView) view.findViewById(R.id.file_path);
        cancel = (Button) view.findViewById(R.id.file_cancel);
        allSelecd = (Button) view.findViewById(R.id.file_allselecd);
        selecedNumber = (TextView) view.findViewById(R.id.file_selenumber);
        longClickLayout = (RelativeLayout) view.findViewById(R.id.file_layout_longclick);
        showLongLayout = (LinearLayout) view.findViewById(R.id.file_showLonglayout);
        upload = (LinearLayout) view.findViewById(R.id.file_layout_upload);
        classify = (LinearLayout) view.findViewById(R.id.file_layout_classify);
        LinearLayout open_layout = (LinearLayout) showLongLayout.getChildAt(0);
        openFile_img = (ImageView) open_layout.getChildAt(0);
        openFile_txt = (TextView) open_layout.getChildAt(1);
        seleedModel = new ArrayList<FileModel>();
    }


    /**
     * 初始化监听
     */
    private void initListener() {
        listview.setOnItemClickListener(this);
        sort.setOnClickListener(this);
        newFile.setOnClickListener(this);
        search.setOnClickListener(this);
        listview.setOnItemLongClickListener(this);
        cancel.setOnClickListener(this);
        allSelecd.setOnClickListener(this);
        upload.setOnClickListener(this);
        classify.setOnClickListener(this);
        //给长按工具界面的功能都设置监听
        for (int i = 0; i < showLongLayout.getChildCount(); i++) {
            showLongLayout.getChildAt(i).setOnClickListener(this);
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Dao db = Dao.getInstance(getActivity());
        mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile(), getActivity());
        listview.setAdapter(mAdapter);
        initGridView();
        initGridView1();
    }

    /**
     * 初始化GridView
     */
    private void initGridView() {
        gviewParent = View.inflate(getActivity(), R.layout.test, null);
        gview = (GridView) gviewParent.findViewById(R.id.gview);
        // 新建List
        data_list = new ArrayList<Map<String, Object>>();
        // 获取数据
        getData();
        // 新建适配器
        String[] from = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.item, from,
                to);
        // 配置适配器
        gview.setAdapter(sim_adapter);

        gview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent;
                switch (position) {
                    case 1:
                        intent = new Intent(getActivity(), UploadMusicActivity.class);
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(getActivity(), UploadPictureActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(getActivity(), UploadVideoActivity.class);
                        startActivity(intent);
                        break;
                    default:
                        Toast.makeText(getActivity(), "并没有实现", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    /**
     * 初始化GridView
     */
    private void initGridView1() {
        gviewParent1 = View.inflate(getActivity().getApplicationContext(), R.layout.test, null);
        gview1 = (GridView) gviewParent1.findViewById(R.id.gview);
        // 新建List
        data_list1 = new ArrayList<Map<String, Object>>();
        // 获取数据
        getDataForClass();
        // 新建适配器
        String[] from = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        sim_adapter1 = new SimpleAdapter(getActivity(), data_list1, R.layout.item, from,
                to);
        // 配置适配器
        gview1.setAdapter(sim_adapter1);
        gview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Intent intent = new Intent(getActivity(), PhotoActivity.class);
                        startActivity(intent);
                        // startActivity(new  Intent(MainActivity.this,Photo.class));
                        break;
                    case 1:
                        startActivity(new Intent(getActivity(), DocumentActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(getActivity(), MusicActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), BtActivity.class));
                        break;
                    case 4:
                        startActivity(new Intent(getActivity(), VideoActivity.class));
                        break;
                    case 5:
                        startActivity(new Intent(getActivity(), ApplicationActivity.class));
                        break;
                    case 6:
                        startActivity(new Intent(getActivity(), OthersActivity.class));
                        break;
                    default:
                        Toast.makeText(getActivity(), "sorry", Toast.LENGTH_SHORT);

                }
                popupWindow1.dismiss();
            }
        });
    }

    /**
     * 获取上传数据
     *
     * @return
     */
    public List<Map<String, Object>> getData() {
        // cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            data_list.add(map);
        }
        return data_list;
    }


    /**
     * 把旧的弹出窗体关闭掉。
     */
    private void dismissPopupWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /**
     * activity销毁时要把冒泡窗体关闭置空
     */
    @Override
    public void onDestroy() {
        dismissPopupWindow();
        super.onDestroy();
    }


    @Override
    public void onResume() {
        dismissPopupWindow();
        super.onResume();
    }

    /**
     * 当点击条目的时候触发
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileModel item = (FileModel) mAdapter.getItem(position);
        if (isLongClick == true) {
            //如果现在是长按状态,则点击的这个设置成选中状态
            item.setIsCheck(!item.isCheck());
            updateAdapter();
            return;
        }
        //点击文件夹
        int type = item.getType();
        if (type == FileConfig.TYPE_FOLDER) {
            //如果是文件夹,则打开文件夹
            mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getFileById(item.getId()), getActivity());
            listview.setAdapter(mAdapter);
            currId = currId + "/" + String.valueOf(item.getId());
            currPosition = currPosition + "/" + position;
            paths += "/" + item.getName();
            tv_path.setText(paths);
        } else {
            Toast.makeText(getActivity(), "打开文件", Toast.LENGTH_SHORT).show();
        }
    }

    private long lastTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {

            if (isLongClick) {
                //如果在长按状态下按了返回，则退出长按状态
                cancelLongClick();
                return false;
            }

            if (currId.equals("0")) {
                //如果已经是目录了，就不退了
                if (System.currentTimeMillis() - lastTime < 2000) {
                    //如果当前时间减去上次的时间，大于2秒
                    getActivity().finish();
                } else {
                    //如果不大于
                    Toast.makeText(getActivity(), "连续按两次退出", Toast.LENGTH_SHORT).show();
                    lastTime = System.currentTimeMillis();
                }
                return false;
            }
            paths = paths.substring(0, paths.lastIndexOf("/"));
            //把当前路径分割，获取当前目录的上一个目录的ID
            String[] split = currId.split("/");
            String[] positons = currPosition.split("/");
            String rsult = split[split.length - 2];
            //如果是0的话，就是返回到主页面了，就要获取所有数据，而不是根据ID获取指定数据
            if (rsult.equals("")) {
                rsult = "0";
            }
            if (Integer.valueOf(rsult) == 0) {
                mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile(), getActivity());
            } else {
                mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getFileById(Integer.valueOf(rsult)), getActivity());
            }
            listview.setAdapter(mAdapter);
            try {
                listview.setSelection(Integer.valueOf(positons[positons.length - 1]));
            } catch (Exception ex) {
                Log.i("info", "转换异常216行");
            }
            tv_path.setText(paths);
            //更新当前路径
            currId = currId.substring(0, currId.length() - 2);
            currPosition = currPosition.substring(0, currPosition.length() - 1);
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.file_sort:
                //排序
                openPopupWindown();
                break;

            case R.id.file_newfile:
                //新建
                newFile();
                break;

            case R.id.file_search:
                //搜索
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;

            case R.id.newfile_yes:
                //确定创建文件夹
                createFolder();
                break;

            case R.id.newfile_cancel:
                //取消
                alertDialog.dismiss();
                break;

            case R.id.order_name:
                //点击了按名字排序
                orderByName();
                break;

            case R.id.order_time:
                //点击了按时间排序
                orderByTime();
                break;

            case R.id.file_cancel:
                //取消
                cancelLongClick();
                break;

            case R.id.file_allselecd:
                //全选
                selecedAll();
                break;

            case R.id.file_more_open:
                //打开文件
                openFile();
                break;

            case R.id.file_more_delete:
                //删除文件
                deleteFile();
                break;

            case R.id.file_more_down:
                //下载文件
                if (currSelseNum > 0) {
                    //如果没有选中东西,则直接退出
                    downLoad();
                }
                break;

            case R.id.file_more_more:
                //更多
                if (currSelseNum <= 0) {
                    //如果没有选中东西,则直接退出
                    break;
                }
                openMore();
                break;

            case R.id.more_move:
                //移动文件
                moveFile();
                break;

            case R.id.more_rename:
                //打开重命名
                if (seleedModel.size() == 1) {
                    openReName();
                    window.dismiss();
                }
                break;


            case R.id.dialog_yes:
                //确定更改名字
                reName();
                break;

            case R.id.dialog_cancel:
                //取消Dialog
                alertDialog.dismiss();
                break;

            case R.id.file_layout_upload:
                //打开上传
                //上传
                popupWindow = new PopupWindow(gviewParent, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                popupWindow.setOutsideTouchable(true);
                popupWindow.setFocusable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                // 动画效果的播放必须要求窗体有背景颜色。
                // 透明颜色也是颜色
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                int[] location = new int[2];
                gview.getLocationInWindow(location);
                ImageView child = (ImageView) gview.findViewById(R.id.image);
                try {
                    popupWindow.showAsDropDown(v, -2, -2);
                } catch (Exception ex) {

                }
                ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
                sa.setDuration(300);
                AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
                aa.setDuration(300);
                AnimationSet set = new AnimationSet(false);
                set.addAnimation(aa);
                set.addAnimation(sa);
//                gview.startAnimation(set);
                break;

            case R.id.file_layout_classify:
                //分类
                popupWindow1 = new PopupWindow(gviewParent1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow1.setOutsideTouchable(true);
                popupWindow1.setFocusable(true);
//                popupWindow1.setBackgroundDrawable(new BitmapDrawable());
                if (popupWindow1.isShowing()) {
                    popupWindow1.dismiss();
                }
                // 动画效果的播放必须要求窗体有背景颜色。
                // 透明颜色也是颜色
                popupWindow1.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                int[] location1 = new int[2];
                gview1.getLocationInWindow(location1);
//                ImageView child = (ImageView) gview.findViewById(R.id.image);
                popupWindow1.showAsDropDown(v, -2, -2);

                ScaleAnimation sa1 = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
                sa1.setDuration(300);
                AlphaAnimation aa1 = new AlphaAnimation(0.5f, 1.0f);
                aa1.setDuration(300);
//                AnimationSet set = new AnimationSet(false);
//                set.addAnimation(aa);
//                set.addAnimation(sa);
//                gview.startAnimation(set);
                break;
        }
    }

    /**
     * 打开分类
     */
    private void openClassify(View v) {
        popupWindow1 = new PopupWindow(gviewParent1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow1.setOutsideTouchable(true);
        popupWindow1.setFocusable(true);
//                popupWindow1.setBackgroundDrawable(new BitmapDrawable());
        if (popupWindow1.isShowing()) {
            popupWindow1.dismiss();
        }
        // 动画效果的播放必须要求窗体有背景颜色。
        // 透明颜色也是颜色
        popupWindow1.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location1 = new int[2];
        gview1.getLocationInWindow(location1);
//                ImageView child = (ImageView) gview.findViewById(R.id.image);
        popupWindow1.showAsDropDown(v, -2, -2);

        ScaleAnimation sa1 = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        sa1.setDuration(300);
        AlphaAnimation aa1 = new AlphaAnimation(0.5f, 1.0f);
        aa1.setDuration(300);
//                AnimationSet set = new AnimationSet(false);
//                set.addAnimation(aa);
//                set.addAnimation(sa);
//                gview.startAnimation(set);
    }

    /**
     * 打开上传
     */
    private void openUpLoad(View v) {
        popupWindow = new PopupWindow(gviewParent, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 动画效果的播放必须要求窗体有背景颜色。
        // 透明颜色也是颜色
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location = new int[2];
        gview.getLocationInWindow(location);
        ImageView child = (ImageView) gview.findViewById(R.id.image);
        try {
            popupWindow.showAsDropDown(v, -2, -2);
        } catch (Exception ex) {

        }
        ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setDuration(300);
        AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
        aa.setDuration(300);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
//                gview.startAnimation(set);
    }

    /**
     * 移动文件
     */
    private void moveFile() {

    }

    /**
     * 重命名
     */
    private void reName() {
        FileModel fileModel = seleedModel.get(0);
        Dao.getInstance(getActivity()).updateName(fileModel.getId(), fileModel.getType(), newFileNmae.getText().toString()+postfix);
        for (FileModel model : mAdapter.getData()) {
            if (model.getId() == fileModel.getId()) {
                model.setName(newFileNmae.getText().toString()+postfix);
            }
        }
        updateAdapter();
        cancelLongClick();
        alertDialog.dismiss();
    }

    /**
     * 下载文件
     */
    private void downLoad() {
        Toast.makeText(getActivity(), "下载文件" + seleedModel.size() + "个", Toast.LENGTH_SHORT).show();
    }

    /**
     * 删除文件
     */
    private void deleteFile() {
        if (currSelseNum >= 1) {
            //如果没有选中东西,则直接退出
            Dao.getInstance(getActivity()).deleteModel(seleedModel);
            mAdapter.getData().removeAll(seleedModel);
            updateAdapter();
            cancelLongClick();
        }
    }

    /**
     * 全选
     */
    private void selecedAll() {
        for (FileModel model : mAdapter.getData()) {
            initModel(model);
            if (isAllSeleced) {
                model.setIsCheck(false);
                model.setIsLoading(true);
            } else {
                model.setIsLoading(false);
                model.setIsCheck(true);
            }
        }
        isAllSeleced = !isAllSeleced;
        updateAdapter();
    }

    /**
     * 根据时间排序
     */
    private void orderByTime() {
        Collections.sort(mAdapter.getData(), new MyFileComparator());
        mAdapter.notifyDataSetChanged();
        window.dismiss();
        order_tiem.setTextColor(getActivity().getResources().getColor(R.color.blue));
        order_name.setTextColor(getActivity().getResources().getColor(R.color.white));
        isTime = true;
    }

    /**
     * 根据名字排序
     */
    private void orderByName() {
        Collections.sort(mAdapter.getData(), new NameComparator());
        updateAdapter();
        window.dismiss();
        order_name.setTextColor(getActivity().getResources().getColor(R.color.blue));
        order_tiem.setTextColor(getActivity().getResources().getColor(R.color.white));
        isTime = false;
    }

    /**
     * 创建文件夹
     */
    private void createFolder() {
        String fileName = newFileNmae.getText().toString().trim();
        if (TextUtils.isEmpty(fileName)) {
            //如果为空
            Toast.makeText(getActivity(), "文件夹名字不可为空", Toast.LENGTH_SHORT).show();
        } else {
            //刷新适配器，进行重新获取数据库
            if (currId.equals(FileConfig.IS_ROOT)) {
                //如果现在是在根目录进行创建，
                Dao.getInstance(getActivity()).newFolder(fileName, FileConfig.IS_FIRST, FileConfig.IS_NOFOLDER_ID);
                //如果在根目录,就进行对根目录的重新获取
                mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile(), getActivity());
            } else {
                //如果不在根目录创建
                String[] split = currId.split("/");
                String rsult = split[split.length - 1];
                Dao.getInstance(getActivity()).newFolder(fileName, FileConfig.IS_OTHER, Integer.valueOf(rsult));
                //如果是子目录，就进行根据子目录的ID进行获取
                mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getFileById(Integer.valueOf(rsult)), getActivity());
            }
            listview.setAdapter(mAdapter);
            alertDialog.dismiss();
        }
    }


    /**
     * 打开重命名窗口
     */
    private void openReName() {
        postfix = "";
        //初始化新建文件夹Dialog的控件
        View dialog_view = getActivity().getLayoutInflater().inflate(R.layout.item_dialog_rename, null);
        Button newFileNo = (Button) dialog_view.findViewById(R.id.dialog_cancel);
        newFileNmae = (EditText) dialog_view.findViewById(R.id.dialog_name);
        Button newFileYes = (Button) dialog_view.findViewById(R.id.dialog_yes);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        FileModel fileModel = seleedModel.get(0);
        String s = fileModel.getName().toString();
        newFileNmae.setText(s.substring(0, s.lastIndexOf(".")));
        postfix = s.substring(s.lastIndexOf("."));
        newFileNmae.selectAll();
        alertDialog = builder.create();
        alertDialog.setView(dialog_view);
        alertDialog.show();
        newFileYes.setOnClickListener(this);
        newFileNo.setOnClickListener(this);
    }

    /**
     * 打开更多
     */
    private void openMore() {
        window = new PopupWindow(getActivity().getResources().getDisplayMetrics().widthPixels / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_pop_more, null);
        view.findViewById(R.id.more_move).setOnClickListener(this);
        view.findViewById(R.id.more_rename).setOnClickListener(this);
        ImageView more_img = (ImageView) view.findViewById(R.id.more_img);
        TextView more_tv = (TextView) view.findViewById(R.id.more_tv_rename);
        window.setContentView(view);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        int[] widthAndHeightforView = FileUtils.getWidthAndHeightforView(showLongLayout);
        window.showAtLocation(showLongLayout, Gravity.RIGHT | Gravity.BOTTOM, 0, widthAndHeightforView[1]);
        if (seleedModel.size() == 1) {
            //说明只有选中一个，可以重命名操作
            more_img.setImageResource(R.mipmap.edit_tools_rename);
            more_tv.setTextColor(getResources().getColor(R.color.white));
        } else {
            more_img.setImageResource(R.mipmap.edit_tools_rename_disable);
            more_tv.setTextColor(getResources().getColor(R.color.disable));
        }
    }

    /**
     * 打开文件
     */
    private void openFile() {
        if (currSelseNum <= 0) {
            //如果没有选中东西,则直接退出
            return;
        }
        if (currSelseNum == 1) {
            //如果选中的等于1,则可以进行打开
            FileModel fileModel = seleedModel.get(0);
            if (fileModel != null) {
                if (fileModel.getType() == FileConfig.TYPE_FOLDER) {
                    //如果是文件夹，就打开文件夹
                    mAdapter = new FileAdapter(Dao.getInstance(getActivity()).getFileById(fileModel.getId()), getActivity());
                    listview.setAdapter(mAdapter);
                    currId = currId + "/" + String.valueOf(fileModel.getId());
                    paths += "/" + fileModel.getName();
                    currPosition = currPosition + "/" + mAdapter.getData().indexOf(fileModel);
                    tv_path.setText(paths);
                    updateAdapter();
                    cancelLongClick();
                } else {
                    Toast.makeText(getActivity(), "打开文件", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 初始化状态
     *
     * @param model
     */
    private void initModel(FileModel model) {
        model.setIsLoading(false);
        model.setIsCheck(false);
        model.setIsSingle(false);
    }


    /**
     * 打开排序选项，PopupWindow
     */
    private void openPopupWindown() {
        window = new PopupWindow(getActivity().getResources().getDisplayMetrics().widthPixels / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_popuorder, null);
        order_name = (TextView) view.findViewById(R.id.order_name);
        order_tiem = (TextView) view.findViewById(R.id.order_time);
        order_name.setOnClickListener(this);
        order_tiem.setOnClickListener(this);
        window.setContentView(view);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        window.showAsDropDown(layout);
        if (isTime) {
            order_tiem.setTextColor(getActivity().getResources().getColor(R.color.blue));
            order_name.setTextColor(getActivity().getResources().getColor(R.color.white));
        } else {
            order_name.setTextColor(getActivity().getResources().getColor(R.color.blue));
            order_tiem.setTextColor(getActivity().getResources().getColor(R.color.white));
        }
    }

    /**
     * 新建文件夹
     */
    private void newFile() {
        //初始化新建文件夹Dialog的控件
        dialog_view = getActivity().getLayoutInflater().inflate(R.layout.item_dialog, null);
        newFileNo = (Button) dialog_view.findViewById(R.id.newfile_cancel);
        newFileNmae = (EditText) dialog_view.findViewById(R.id.newfile_name);
        newFileYes = (Button) dialog_view.findViewById(R.id.newfile_yes);
        builder = new AlertDialog.Builder(getActivity());
        alertDialog = builder.create();
        alertDialog.setView(dialog_view);
        alertDialog.show();
        newFileYes.setOnClickListener(this);
        newFileNo.setOnClickListener(this);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (isLongClick == false) {
            //如果现在不是长按状态,则进行长按操作
            List<FileModel> data = mAdapter.getData();
            //把所有条目的对象都设置成等待选中状态
            for (FileModel model : data) {
                model.setIsCheck(false);
                model.setIsLoading(false);
                model.setIsSingle(false);
                model.setIsLoading(true);
            }
            //把当前长按的这个条目设置为选中状态
            data.get(position).setIsCheck(true);
            updateAdapter();
            isLongClick = true;
            //设置长按界面开启
            longClickLayout.setVisibility(View.VISIBLE);
            showLongLayout.setVisibility(View.VISIBLE);
            //标题隐藏
            layout.setVisibility(View.INVISIBLE);
            return true;
        }
        return false;
    }

    /**
     * 退出长按事件
     */
    public void cancelLongClick() {
        List<FileModel> data = mAdapter.getData();
        for (FileModel model : data) {
            model.setIsSingle(true);
        }
        updateAdapter();
        isLongClick = false;
        layout.setVisibility(View.VISIBLE);
        longClickLayout.setVisibility(View.INVISIBLE);
        showLongLayout.setVisibility(View.GONE);
    }

    /**
     * 更新适配器
     */
    public void updateAdapter() {
        seleedModel.clear();
        mAdapter.notifyDataSetChanged();
        int selecedIndex = 0;
        for (FileModel model : mAdapter.getData()) {
            if (model.isCheck()) {
                selecedIndex++;
                seleedModel.add(model);
            }
        }
        selecedNumber.setText("已选中" + selecedIndex + "个");
        currSelseNum = selecedIndex;
        for (int i = 0; i < showLongLayout.getChildCount(); i++) {
            LinearLayout childAt = (LinearLayout) showLongLayout.getChildAt(i);
            ImageView img = (ImageView) childAt.getChildAt(0);
            TextView txt = (TextView) childAt.getChildAt(1);
            img.setImageResource(selecedIndex >= 1 ? img_white[i] : img_grey[i]);
            txt.setTextColor(selecedIndex >= 1 ? getResources().getColor(R.color.white) : getResources().getColor(R.color.grey));
        }
        if (selecedIndex > 1) {
            openFile_img.setImageDrawable(getResources().getDrawable(R.drawable.open_grey));
            openFile_txt.setTextColor(getResources().getColor(R.color.grey));
        }
    }


    public List<Map<String, Object>> getDataForClass() {
        // cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon1.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon1[i]);
            map.put("text", iconName1[i]);
            data_list1.add(map);
        }
        return data_list1;
    }

    /**
     * 把旧的弹出窗体关闭掉。
     */
    private void dismissPopupWindowForClass() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }

        if (popupWindow1 != null && popupWindow1.isShowing()) {
            popupWindow1.dismiss();
            popupWindow1 = null;
        }
    }

}
